import 'package:flutter/material.dart';
import 'package:flutter_rtk/api/api.dart';
import 'package:flutter_rtk/common/assets.dart';
import 'package:flutter_rtk/common/common.dart';
import 'package:flutter_rtk/common/constants.dart';
import 'package:flutter_rtk/components/refresh_list_widget.dart';
import 'package:flutter_rtk/entities/current_project_entity.dart';
import 'package:flutter_rtk/entities/message_page_entity.dart';
import 'package:flutter_rtk/models/app_model.dart';
import 'package:flutter_rtk/router/index.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

class MessagePage extends StatefulWidget {
  const MessagePage({super.key});

  @override
  State<MessagePage> createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int _currentIdx = 0;

  CurrentProjectEntity? _currentProjectInfo;
  MessagePageEntity? _totalMessagePage;
  MessagePageEntity? _readMessagePage;
  MessagePageEntity? _unReadMessagePage;

  _buildMainView() {
    return Scaffold(
      appBar: mainAppBar(title: "消息"),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        margin: EdgeInsets.only(top: 20.h),
        child: Container(
          width: double.infinity,
          height: double.infinity,
          color: Colors.white,
          child: Column(children: [
            Padding(
              padding: EdgeInsets.all(25.w),
              child: _buildSwitchBar(),
            ),
            Expanded(
              child: TabBarView(controller: _tabController, children: [
                _buildMessageByStatus(_unReadMessagePage),
                _buildMessageByStatus(_readMessagePage),
                _buildMessageByStatus(_totalMessagePage),
              ]),
            ),
          ]),
        ),
      ),
    );
  }

  _buildMessageByStatus(MessagePageEntity? messagePageEntity) {
    if (messagePageEntity == null) {
      return const Center(child: Text("信息加载中"));
    }
    return Container(
      width: double.infinity,
      height: 405.h * 3,
      alignment: Alignment.center,
      child: Scrollbar(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 25.w),
          child: RefreshListWidget(
            itemBuilder: (item) {
              return Padding(
                padding: EdgeInsets.symmetric(horizontal: 25.w),
                child: InkWell(
                  onTap: () => Navigator.pushNamed(context, AppRouters.toMessageDetailPage, arguments: {"messageId": item.msgId, "title": item.msgTile}),
                  child: _buildMessageItem(item),
                ),
              );
            },
            separatorBuilder: (idx) => const SizedBox.shrink(),
            dataList: messagePageEntity.records,
            onRefresh: () => _doRefreshList(),
            onLoading: messagePageEntity.current < messagePageEntity.pages ? () => _doLoadingList(current: messagePageEntity.current + 1) : null,
          ),
        ),
      ),
    );
  }

  _buildMessageItem(MessageInfo item) {
    return Container(
      width: double.infinity,
      height: 90.h,
      decoration: BoxDecoration(border: Border(bottom: BorderSide(color: const Color(0xFFE7E7E7), width: 1.h))),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        SizedBox(width: 40.w, height: 40.h, child: Image.asset(AppAssets.minePhone)),
        SizedBox(width: 12.w),
        Expanded(
          child: Text("${item.msgTile} ${item.msgContent}", style: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.normal, color: Colors.black), overflow: TextOverflow.ellipsis),
        ),
        SizedBox(width: 12.w),
        Row(children: [
          Text(item.startDate.substring(0, 10), style: TextStyle(fontSize: 24.sp, fontWeight: FontWeight.normal, color: const Color(0xFF8B8B8B))),
          SizedBox(width: 8.w),
          Container(width: 8.w, height: 8.w, decoration: BoxDecoration(color: const Color(0xFF8B8B8B), borderRadius: BorderRadius.circular(8.r))),
          SizedBox(width: 10.w),
          SizedBox(width: 9.w, height: 18.h, child: Image.asset(AppAssets.mineRightArrow)),
        ])
      ]),
    );
  }

  Container _buildSwitchBar() {
    return Container(
      width: 700.w,
      height: 68.h,
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(10.r), border: Border.all(color: AppConstants.brandColor)),
      child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
        Flexible(
          flex: 1,
          child: _buildSwitchBarItem(
            text: _unReadMessagePage != null ? "未读(${_unReadMessagePage!.total})" : "未读(--)",
            idx: 0,
            onTap: () {
              setState(() {
                _currentIdx = 0;
              });
              _tabController.animateTo(0);
            },
          ),
        ),
        Flexible(
          flex: 1,
          child: _buildSwitchBarItem(
            text: _readMessagePage != null ? "已读(${_readMessagePage!.total})" : "已读(--)",
            idx: 1,
            onTap: () {
              setState(() {
                _currentIdx = 1;
              });
              _tabController.animateTo(1);
            },
          ),
        ),
        Flexible(
          flex: 1,
          child: _buildSwitchBarItem(
            text: _totalMessagePage != null ? "全部(${_totalMessagePage!.total})" : "全部(--)",
            idx: 2,
            onTap: () {
              setState(() {
                _currentIdx = 2;
              });
              _tabController.animateTo(2);
            },
          ),
        ),
      ]),
    );
  }

  _buildSwitchBarItem({required String text, required Function() onTap, required int idx}) {
    BoxDecoration? decoration;
    if (_currentIdx == 0) {
      if (idx == 1) {
        decoration = const BoxDecoration(border: Border(right: BorderSide(color: AppConstants.brandColor)));
      }
    } else if (_currentIdx == 2) {
      if (idx == 0) {
        decoration = const BoxDecoration(border: Border(right: BorderSide(color: AppConstants.brandColor)));
      }
    }
    if (idx == _currentIdx) {
      return Container(
        width: double.infinity,
        height: double.infinity,
        alignment: Alignment.center,
        color: AppConstants.brandColor,
        child: Text(text, style: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.w600, color: Colors.white)),
      );
    }
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        child: Container(
          width: double.infinity,
          height: double.infinity,
          alignment: Alignment.center,
          decoration: decoration,
          child: Text(text, style: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.w600, color: AppConstants.brandColor)),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildMainView();
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _currentProjectInfo = context.read<AppModel>().currentProjectInfo;
    _fetchMessageList(
      projectId: _currentProjectInfo!.projectId,
      projectCode: _currentProjectInfo!.projectCode,
      callback: (messageInfo) {
        setState(() {
          _totalMessagePage = messageInfo;
        });
      },
    );
    // 未读
    _fetchMessageList(
      projectId: _currentProjectInfo!.projectId,
      projectCode: _currentProjectInfo!.projectCode,
      isRead: 1,
      callback: (messageInfo) {
        setState(() {
          _unReadMessagePage = messageInfo;
        });
      },
    );
    // 已读
    _fetchMessageList(
      projectId: _currentProjectInfo!.projectId,
      projectCode: _currentProjectInfo!.projectCode,
      isRead: 0,
      callback: (messageInfo) {
        setState(() {
          _readMessagePage = messageInfo;
        });
      },
    );
  }

  _fetchMessageList({int current = 1, int? isRead, required String projectId, required String projectCode, required Function(MessagePageEntity messageInfo) callback}) async {
    try {
      var messagePageEntity = await AppApi.getMessagePage(current: current, isRead: isRead);
      callback(messagePageEntity);
    } catch (e) {
      debugPrint("获取消息列表失败: $e");
      showToast("获取消息列表失败:$e");
    }
  }

  _doRefreshList() {
    if (_currentIdx == 0) {
      // 未读
      return _fetchMessageList(
        projectId: _currentProjectInfo!.projectId,
        projectCode: _currentProjectInfo!.projectCode,
        isRead: 1,
        callback: (messageInfo) {
          setState(() {
            _unReadMessagePage = messageInfo;
          });
        },
      );
    } else if (_currentIdx == 1) {
      // 已读
      return _fetchMessageList(
        projectId: _currentProjectInfo!.projectId,
        projectCode: _currentProjectInfo!.projectCode,
        isRead: 0,
        callback: (messageInfo) {
          setState(() {
            _readMessagePage = messageInfo;
          });
        },
      );
    }
    return _fetchMessageList(
      projectId: _currentProjectInfo!.projectId,
      projectCode: _currentProjectInfo!.projectCode,
      callback: (messageInfo) {
        setState(() {
          _totalMessagePage = messageInfo;
        });
      },
    );
  }

  _doLoadingList({int current = 1}) {
    if (_currentIdx == 0) {
      // 未读
      return _fetchMessageList(
        projectId: _currentProjectInfo!.projectId,
        projectCode: _currentProjectInfo!.projectCode,
        isRead: 1,
        current: current,
        callback: (MessagePageEntity messageInfo) {
          setState(() {
            MessagePageEntity oldEntity = _unReadMessagePage!;
            messageInfo.records.insertAll(0, oldEntity.records);
            _unReadMessagePage = messageInfo;
          });
        },
      );
    } else if (_currentIdx == 1) {
      // 已读
      return _fetchMessageList(
        projectId: _currentProjectInfo!.projectId,
        projectCode: _currentProjectInfo!.projectCode,
        isRead: 0,
        current: current,
        callback: (messageInfo) {
          setState(() {
            MessagePageEntity oldEntity = _readMessagePage!;
            messageInfo.records.insertAll(0, oldEntity.records);
            _readMessagePage = messageInfo;
          });
        },
      );
    }
    return _fetchMessageList(
      projectId: _currentProjectInfo!.projectId,
      projectCode: _currentProjectInfo!.projectCode,
      current: current,
      callback: (messageInfo) {
        setState(() {
          MessagePageEntity oldEntity = _totalMessagePage!;
          messageInfo.records.insertAll(0, oldEntity.records);
          _totalMessagePage = messageInfo;
        });
      },
    );
  }
}
